<template>
  <div class="image-success">
    <div class="image-success__image">
      <img :src="value" />
    </div>
    <div class="image-success__upload">
      <StyleUpload
        @success="handleStyleUploadSuccess"
        :showupload-list="false"
        :upload-class="true"
      />
      <a-button
        class="image-success__upload__btn"
        @click="handleCropImgHandler"
      >
        <template #icon>
          <scissor-outlined />
        </template>
        裁剪图片
      </a-button>
      <a-button
        @click="handleDeleteImg"
        v-if="showDelete"
        type="primary"
        danger
      >
        <template #icon>
          <delete-outlined />
        </template>
        删除图片
      </a-button>
    </div>
    <a-modal
      v-model:open="imageUploadVisible"
      title="裁剪图片"
      @ok="cropperOkHandler"
      okText="确定"
      cancelText="取消"
    >
      <!-- <a-spin v-if="cropperLoading" /> -->
      <a-spin :spinning="cropperLoading">
        <div class="image-crop__image">
          <img :src="baseImageUrl" id="image_crop" ref="imageCrop" />
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'ImageSuccess',
})
interface ImageSuccessProps {
  value: string
  showDelete?: boolean
  changeType?: 'component' | 'page'
}
interface ICropperDetailProps {
  x: number
  y: number
  width: number
  height: number
}
import { ref, watch, nextTick, computed } from 'vue'
import { ScissorOutlined, DeleteOutlined } from '@ant-design/icons-vue'
//引入cropper
import Cropper from 'cropperjs'
import { getImageInfo } from '@/helper'
import StyleUpload from './stylUpload.vue'
import useEditorStore from '@/store/modules/editorStore'
const { changeCurrentComponentProps, changePageData } = useEditorStore()
const props = withDefaults(defineProps<ImageSuccessProps>(), {
  changeType: 'component',
})
const emits = defineEmits(['change'])
const imageUploadVisible = ref(false)
const imageCrop = ref<null | HTMLImageElement>(null)
const cropperLoading = ref(false)
const baseImageUrl = computed(() => {
  return props.value.split('?')[0]
})
const cropperDetailProps = ref<ICropperDetailProps | null>(null)
const handleStyleUploadSuccess = (data: any) => {
  const { res } = data
  const srcValue =
    Array.isArray(res.data) && res.data.length > 0 ? res.data[0] : res.data
  getImageInfo(data.file).then(({ width, height }) => {
    const maxWidth = 375
    const minHeight = 560
    const imgWidth = width > maxWidth ? maxWidth + 'px' : width + 'px'
    const pageHeight = height < minHeight ? minHeight : height
    emits('change', srcValue)
    if (props.changeType === 'component') {
      changeCurrentComponentProps({ key: 'width', value: imgWidth })
      changeCurrentComponentProps({ key: 'src', value: srcValue })
      changeCurrentComponentProps({ key: 'imageSrc', value: srcValue })
    } else {
      setTimeout(() => {
        changePageData({ key: 'height', value: pageHeight + 'px' })
      }, 320)
    }
  })
}
/**cropper实例*/
const cropper = ref<null | Cropper>(null)
watch(imageUploadVisible, (newValue) => {
  // 监听imageUploadVisible的变化
  if (newValue) {
    // 如果newValue为true
    nextTick(() => {
      // 在下一个DOM更新周期中执行
      if (imageCrop.value) {
        // 如果imageCrop存在
        cropperLoading.value = true
        // 设置cropperLoading为true
        cropper.value = new Cropper(imageCrop.value, {
          // 创建一个新的Cropper实例
          crop(event: any) {
            // 监听裁剪事件
            const { x, y, width, height } = event.detail
            // 获取裁剪后的坐标和尺寸
            cropperDetailProps.value = {
              x: Math.floor(x),
              y: Math.floor(y),
              width: Math.floor(width),
              height: Math.floor(height),
            }
            // 设置裁剪后的坐标和尺寸
            cropperLoading.value = false
            // 设置cropperLoading为false
          },
        })
      }
    })
  } else {
    // 如果newValue为false
    if (cropper.value) {
      // 如果cropper存在
      cropper.value.destroy()
      // 销毁cropper实例
    }
  }
})
/** 裁剪图片对话框*/
const handleCropImgHandler = () => {
  imageUploadVisible.value = true
}
/**
 * 裁剪图片确定的回调
 */
const cropperOkHandler = () => {
  //1.拼接出裁剪的图片URL
  const { x, y, width, height } = cropperDetailProps.value || {}
  const cropImageUrl =
    baseImageUrl.value +
    `?x-oss-process=image/crop,x_${x},y_${y},w_${width},h_${height}`
  //2.触发emits事件，将裁剪的图片URL传递给父组件
  emits('change', cropImageUrl)
  //3.关闭裁剪图片对话框
  imageUploadVisible.value = false
}
const handleDeleteImg = () => {
  emits('change', '')
}
</script>

<style scoped lang="scss">
.image-success {
  width: 100%;
  height: 100%;
  display: flex;
  .image-success__image {
    flex: 1;
    height: 120px;
    text-align: center;
    border: 1px dashed #ccc;
    overflow: hidden;
    img {
      height: 100%;
    }
  }
  .image-success__upload {
    flex: 1;
    margin-left: 10px;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    .image-success__upload__btn {
      margin: 5px 0px;
    }
  }
}
.image-crop__image img {
  display: block;
  max-width: 100%;
}
</style>
